package com.wentao.thisService.common.upload;

import com.aliyun.oss.OSSClient;
import com.aliyun.oss.model.ObjectMetadata;
import com.aliyun.oss.model.PutObjectResult;
import org.apache.commons.io.FilenameUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.io.InputStream;
import java.net.URL;
import java.util.Date;
import java.util.UUID;

@Component
public class AliyunOSSUtil {
    /* @Autowired
    private static OssUploadProperties prop;*/
    //此部分参数值需要购买阿里云服务才能写入相应参数

    @Value("${upload.oss.end_point}")
    public String OSS_END_POINT;
    //OSS 的key值
    @Value("${upload.oss.access_key_id}")
    public String OSS_ACCESS_KEY_ID;
    //OSS 的secret值
    @Value("${upload.oss.access_key_secret}")
    public String OSS_ACCESS_KEY_SECRET;
    //OSS 的bucket名字
    @Value("${upload.oss.bucket_name}")
    public String OSS_BUCKET_NAME;

    //设置URL过期时间为1小时（可自定义）
    private final static Date OSS_URL_EXPIRATION = new Date(new Date().getTime() + 3600 * 1000);
    private static OSSClient instance;


    /**
     * @return OSS工具类实例
     */
    private OSSClient getOSSClient() {
        if (instance == null) {
            instance = new OSSClient(OSS_END_POINT, OSS_ACCESS_KEY_ID, OSS_ACCESS_KEY_SECRET);
        }
        return instance;
    }

    /**
     * 文件上传代码
     */
    public String upload(MultipartFile file) throws Exception {
        createBucket();
        String fileName = uploadFile(file);
        String fileOssURL = getImgUrl(fileName);//文件的访问地址
        int firstChar = fileOssURL.indexOf("?");
        if (firstChar > 0) {
            fileOssURL = fileOssURL.substring(0, firstChar);
        }
        return fileOssURL;
    }


    /**
     * 当Bucket不存在时创建Bucket
     */
    private void createBucket() throws Exception {
        try {
            if (!getOSSClient().doesBucketExist(OSS_BUCKET_NAME)) {//判断是否存在该Bucket，不存在时再重新创建
                getOSSClient().createBucket(OSS_BUCKET_NAME);
            }
        } catch (Exception e) {
           e.printStackTrace();
        }
    }


    /**
     * 上传到OSS服务器  如果同名文件会覆盖服务器上的
     */
    private String uploadFile(MultipartFile file) throws Exception {
        String fileName = String.format(
                "%s.%s",
                UUID.randomUUID().toString(),
                FilenameUtils.getExtension(file.getOriginalFilename()));
        try (InputStream inputStream = file.getInputStream()) {
            //创建上传Object的Metadata
            ObjectMetadata objectMetadata = new ObjectMetadata();
            objectMetadata.setContentLength(inputStream.available());
            objectMetadata.setCacheControl("no-cache");
            objectMetadata.setHeader("Pragma", "no-cache");
            objectMetadata.setContentType(getContentType(FilenameUtils.getExtension("." + file.getOriginalFilename())));
            objectMetadata.setContentDisposition("inline;filename=" + fileName);
            //上传文件
            PutObjectResult putResult = getOSSClient().putObject(OSS_BUCKET_NAME, fileName, inputStream, objectMetadata);
            return fileName;//文件的访问地址
        } catch (Exception e) {
            throw new Exception("上传文件失败");
        }
    }


    /**
     * 获得文件路径
     */
    private String getImgUrl(String fileUrl) throws Exception {
        if (StringUtils.isEmpty(fileUrl)) {
            throw new Exception("文件地址为空");
        }
        String[] split = fileUrl.split("/");

        //获取oss图片URL失败
        URL url = getOSSClient().generatePresignedUrl(OSS_BUCKET_NAME, split[split.length - 1], OSS_URL_EXPIRATION);
        if (url == null) {
            throw new Exception("获取oss文件URL失败");
        }
        return url.toString();
    }

    /**
     * 判断OSS服务文件上传时文件的contentType，可根据实际需求增减,FilenameExtension 为文件后缀
     */
    private String getContentType(String FilenameExtension) {
        if (FilenameExtension.equalsIgnoreCase("bmp")) {
            return "image/bmp";
        }
        if (FilenameExtension.equalsIgnoreCase("gif")) {
            return "image/gif";
        }
        if (FilenameExtension.equalsIgnoreCase("jpeg") ||
                FilenameExtension.equalsIgnoreCase("jpg") ||
                FilenameExtension.equalsIgnoreCase("png")) {
            return "image/jpeg";
        }
        if (FilenameExtension.equalsIgnoreCase("html")) {
            return "text/html";
        }
        if (FilenameExtension.equalsIgnoreCase("txt")) {
            return "text/plain";
        }
        if (FilenameExtension.equalsIgnoreCase("vsd")) {
            return "application/vnd.visio";
        }
        if (FilenameExtension.equalsIgnoreCase("pptx") ||
                FilenameExtension.equalsIgnoreCase("ppt")) {
            return "application/vnd.ms-powerpoint";
        }
        if (FilenameExtension.equalsIgnoreCase("docx") ||
                FilenameExtension.equalsIgnoreCase("doc")) {
            return "application/msword";
        }
        if (FilenameExtension.equalsIgnoreCase("xml")) {
            return "text/xml";
        }
        return "image/jpeg";
    }
}
